import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.ApiModelProperty;
import lombok.Getter;
import lombok.Setter;

import java.io.Serializable;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Scanner;

public class RegionUtil {
    /**
     * 开发者密钥
     *
     */
    private interface AccessKey{
        String BD_SERVICE_API = "？？？？";
        String GD_JS_API = "？？？";
    }

    public static void main(String[] args) {
        Address pca = getBDAddress("24.483892", "118.182171");
        System.out.println(JSONObject.toJSONString(pca));

        Address address = getGDAddress("24.492323", "118.137211");
        System.out.println(JSONObject.toJSONString(address));
    }


    /**
     * 百度地图-根据经纬度获取详细地址
     */
    public static Address getBDAddress(String lat, String lng) {
        StringBuilder path = new StringBuilder()
                .append("http://api.map.baidu.com/geocoder/v2/?ak=")
                .append(AccessKey.BD_SERVICE_API).append("&location=").append(lat).append(",").append(lng).append("&output=json");
        HttpURLConnection con = null;
        try {
            URL url = new URL(path.toString());
            con = (HttpURLConnection) url.openConnection();
            con.setRequestMethod("GET");
            con.setRequestProperty(
                    "User-Agent",
                    "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.104 Safari/537.36");
            con.setRequestProperty("Referer", "http://api.map.baidu.com/geocoder/v2/");
            String b = "0",c= "{",d="status";
            String responseBody = new Scanner(con.getInputStream(), "utf-8").useDelimiter("\\A").next();
            //LogUtil.logErr("getGDAddress: res=" + responseBody);

            JSONObject jsonObject = JSONObject.parseObject(responseBody);

            if (!b.equals(jsonObject.getString(d))) {
                throw new RuntimeException("根据经纬度获取详细地址失败");
            }
            if (!responseBody.startsWith(c)) {
                throw new RuntimeException("根据经纬度获取详细地址失败");
            }
            return JSONObject.parseObject(jsonObject.getJSONObject("result").getString("addressComponent"), Address.class);
        } catch (Exception e) {
            //LogUtil.logErr("get info error,  catch exception info: message=" + e.getMessage());
        }finally {
            if (null != con){
                con.disconnect();
            }
        }
        throw new RuntimeException("根据经纬度获取详细地址失败");
    }


    /**
     * 高德地图--根据经纬度获取详细地址
     */
    public static Address getGDAddress(String lat, String lng) {
        String location = lng + "," + lat;
        String jsonp = "jsonp_383775_";
        String urlString = "http://restapi.amap.com/v3/geocode/regeo?key="+AccessKey.GD_JS_API+"&s=rsv3&location="+location+"&radius=1000&callback="+jsonp+"&platform=JS&logversion=2.0&sdkversion=1.4.15&appname=http%3A%2F%2Flbs.amap.com%2Fconsole%2Fshow%2Fpicker&csid=5DF11A07-FC1F-4A5D-9E17-DF450BE76D7A";
        HttpURLConnection conn = null;
        try {
            URL url = new URL(urlString);
            conn = (HttpURLConnection)url.openConnection();
            conn.setDoOutput(true);
            conn.setRequestMethod("GET");
            conn.setRequestProperty(
                    "User-Agent",
                    "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.198 Safari/537.36");
            conn.setRequestProperty("Referer", "https://lbs.amap.com/");
            String responseBody = new Scanner(conn.getInputStream(), "utf-8").useDelimiter("\\A").next();

            if (!responseBody.startsWith(jsonp)) {
                throw new RuntimeException("根据经纬度获取详细地址失败");
            }

            String res = responseBody.substring(jsonp.length() + 1, responseBody.length() - 2);
            //LogUtil.logErr("getGDAddress: res=" + res);

            JSONObject jsonObject = JSONObject.parseObject(res);
            String SUCCESS_KEY = "info", SUCCESS_CODE = "OK";
            if (!SUCCESS_CODE.equals(jsonObject.getString(SUCCESS_KEY))) {
                throw new RuntimeException(jsonObject.getString(SUCCESS_KEY));
            }

            return JSONObject.parseObject(jsonObject.getJSONObject("regeocode").getString("addressComponent"), Address.class);
        } catch (Exception e) {
            //LogUtil.logErr("get info error,  catch exception info: message=" + e.getMessage());
        }finally {
            if (null != conn){
                conn.disconnect();
            }
        }
        throw new RuntimeException("根据经纬度获取详细地址失败");
    }


    @Setter
    @Getter
    public static class Address implements Serializable {
        @ApiModelProperty("国家")
        private String country;

        @ApiModelProperty("市")
        private String city;

        @ApiModelProperty("区编码")
        private String adcode;

        @ApiModelProperty("省")
        private String province;

        @ApiModelProperty("区")
        private String district;
    }

}
